#include "receive.h"
#include "usart.h"
#include "stdio.h"

PARAMTER_USART receive = {
  0,{0},0,USART_RECEIVE_STATE_FREE
};

void RECEIVE_Start(void)
{
  receive.RxData = 0;
  receive.RxState = USART_RECEIVE_STATE_FREE;
  HAL_UART_Receive_IT(&RECEIVE_USART, &(receive.RxData), 1);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  UNUSED(huart);
  
  if(receive.RxState == USART_RECEIVE_STATE_FREE && receive.RxData == USART_RX_START_FLAG)
  {
    receive.RxState = USART_RECEIVE_STATE_START;
    receive.RxBufLen = 0;
  }
  else if(receive.RxState == USART_RECEIVE_STATE_START)
  {
    if(receive.RxData == USART_RX_END_FLAG)
    {
      receive.RxState = USART_RECEIVE_STATE_DONE;
      receive.RxBuffer[receive.RxBufLen++] = '\0';
    }
    else
    {
      receive.RxBuffer[receive.RxBufLen] = receive.RxData;
      if(receive.RxBufLen == USART_RX_BUFFER_LEN-2)
      {
        receive.RxState = USART_RECEIVE_STATE_OVER;
        receive.RxBuffer[receive.RxBufLen++] = '\0';
      }
      else
      {
        receive.RxBufLen++;
      }
    }
  }
  receive.RxData = 0;
  HAL_UART_Receive_IT(&RECEIVE_USART, &(receive.RxData), 1);
}


